package producerconsumer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *Description:
 *Version:1.0.0
 *@author shihb
 *@date 2020/5/23 21:34
 */
public class Juc {
  public static void main(String[] args) {
    Calculate2 c = new Calculate2();
    new Thread(()->{
      for (int i = 0; i < 10; i++) {
        try {
          c.increasing();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    },"A").start();
    new Thread(()->{
      for (int i = 0; i < 10; i++) {
        try {
          c.decreasing();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    },"B").start();


    new Thread(()->{
      for (int i = 0; i < 10; i++) {
        try {
          c.increasing();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    },"C").start();
    new Thread(()->{
      for (int i = 0; i < 10; i++) {
        try {
          c.decreasing();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    },"D").start();

  }

}
class Calculate2 {
  private int num=0;

  private Lock lock = new ReentrantLock();
  private Condition condition = lock.newCondition();
  public  void  increasing() throws InterruptedException {

    lock.lock();
    try {
      while (num!=0){
        condition.await();
      }
      num++;
      System.out.println(Thread.currentThread().getName()+"=>"+num);
      condition.signalAll();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }finally {
      lock.unlock();
    }

  }
  public  void decreasing() throws InterruptedException {
    lock.lock();
    try {
      while (num==0){
        condition.await();
      }
      num--;
      System.out.println(Thread.currentThread().getName()+"=>"+num);
      condition.signalAll();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }finally {
      lock.unlock();
    }
  }
}
